import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { LocalStorageService } from '../../../utils/storage';
import { LoginApi } from "../../../api";
import { message } from 'antd';
import router from '@/router'

interface UserState {
  token: string | null;
  loading: string
  remember: boolean
  password: string
  userName: string
  name?: string
}
const initialState: UserState = {
  token: LocalStorageService.get("token") || null,
  loading: 'idle',
  remember: true,
  userName: LocalStorageService.get("userName") || '',
  password: LocalStorageService.getCookie("password") || '',
  name: LocalStorageService.getCookie("password") || '',

}
export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setRemember: (state, { payload }) => {
      state.remember = payload
    },
    setUserName: (state, { payload }) => {
      state.userName = payload
      LocalStorageService.set("userName", payload)
    },
    setPassword: (state, { payload }) => {
      state.password = payload
      const inFifteenMinutes = new Date(new Date().getTime() + 24 * 3600 * 1000);
      LocalStorageService.setCookie("password", payload, { expires: inFifteenMinutes })
    },
    logOut: (state) => {
      state.token = ''
      LocalStorageService.remove("token")
      router.navigate('/login', { replace: true })
    },

  },
  extraReducers: (builder) => {
    builder
      .addCase(login.pending, (state) => {
        state.loading = 'loading';
      })
      .addCase(login.fulfilled, (state, action: PayloadAction<any>) => {
        state.loading = 'succeeded';
        state.token = action.payload
        LocalStorageService.set("token", action.payload)
        message.success('登录成功')
      })
      .addCase(login.rejected, (state) => {
        state.loading = 'failed';
      });
  },
})

const login = createAsyncThunk('auth/login', async (data: any) => {
  const response = await LoginApi(data)
  return response
})

export { login }
export const { setRemember, setPassword, setUserName, logOut } = authSlice.actions
export default authSlice.reducer;